package com.dhcc.utils;

import java.util.Iterator;
import java.util.ServiceLoader;

import com.dhcc.utils.objects.DefaultObjectFactory;
import com.dhcc.utils.objects.NoSuchBeanException;
import com.dhcc.utils.objects.ObjectFactory;

/**
 * 对象容器（基于SPI）
 * 
 * @author hibean@qq.com 2017年9月11日
 *
 */
public class __Objects {
	private static ObjectFactory factory;
	static{
		try{
			ServiceLoader<ObjectFactory> loader = ServiceLoader.load(ObjectFactory.class);
			Iterator<ObjectFactory> it = loader.iterator();
			if(it.hasNext()){
				factory = it.next();
			}else{
				factory = new DefaultObjectFactory();
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	/**
	 * 获取容器中的实例
	 * 
	 * @param cls
	 * @return
	 */
	public static <T> T getBean(Class<? extends T> cls) {
		Object obj = factory.getObjectByType(cls);
		if(obj == null){
			throw new NoSuchBeanException(null, cls);
		}
		return (T)obj;
	}

	/**
	 * 获取容器中的实例
	 * 
	 * @param beanName
	 *            实例名
	 * @return
	 */
	public static <T> T getBean(String beanName) {
		Object obj = factory.getObjectByName(beanName);
		if(obj == null){
			throw new NoSuchBeanException(beanName, null);
		}
		return (T)obj;
	}

	/**
	 * 获取容器中的实例
	 * 
	 * @param cls 类/接口
	 * @param beanName 实例名
	 * @return
	 */
	public static <T> T getBean(String beanName, Class<? extends T> cls) {
		Object obj  = factory.getObjectByName(beanName);
		if(cls != null && cls.isInstance(obj)){
			return (T)obj;
		}
		throw new NoSuchBeanException(beanName, cls);
	}
}
